package com.dag.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  代码生成器
 */
public class CodeGenerator {

    AutoGenerator autoGenerator = new AutoGenerator();
    String root = "admin";
    String password = "admin123456";
    String url = "jdbc:mysql://120.27.225.120:3306/dag-v2?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
    String parent = "com.dag";
    String moduleName = "account";             // TODO 改为自己的模块
    String[] tablePrefix = {"acc_"};       // TODO 改为自己的表前缀
    String[] include = {"acc_settle_bill", "acc_settle_bill_item"}; // TODO 改为自己的表
    String[] exclude = {};                  //排除生成的表
    boolean fileOverride=false;           // TODO 注意代码是否被重新生成 true表示覆盖代码重新生成
    boolean activeRecord=false;
    InjectionConfig injectionConfig;
    @Before
    public void init(){
        injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object> ();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir")+"/src/main/java");
        globalConfig.setFileOverride(fileOverride);
        globalConfig.setActiveRecord(activeRecord);
        globalConfig.setEnableCache(false);// XML 二级缓存
        globalConfig.setBaseResultMap(true);// XML ResultMap
        globalConfig.setBaseColumnList(true);// XML columList
        globalConfig.setAuthor(System.getProperty("user.name")); // 设置作者
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        globalConfig.setServiceImplName("%sServiceImpl");
        globalConfig.setControllerName("%sApi");
        autoGenerator.setGlobalConfig(globalConfig);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername(root);
        dsc.setPassword(password);
        dsc.setUrl(url);
        autoGenerator.setDataSource(dsc);
    }

    /**
     * 代码自动生成方法 运行即可 注意备份代码
     */
    @Test
    public void doGenerator(){
        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setTablePrefix(tablePrefix);// 此处可以修改为您的表前缀
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategyConfig.setInclude(include); // 需要生成的表
        strategyConfig.setExclude(exclude); // 排除生成的表
        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setRestControllerStyle(false);
        strategyConfig.setEntityBuilderModel(true);
        strategyConfig.setSuperEntityClass("com.dag.common.entity.DataEntity");
        strategyConfig.setSuperEntityColumns("id", "org_id", "merchant_id",
                "creater_id", "create_time", "updater_id", "update_time", "is_delete", "remarks");
        strategyConfig.setSuperMapperClass("com.baomidou.mybatisplus.mapper.BaseMapper");
        strategyConfig.setSuperServiceImplClass("com.baomidou.mybatisplus.service.impl.ServiceImpl");
        autoGenerator.setStrategy(strategyConfig);

        // 包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent(parent);
        packageConfig.setModuleName(moduleName);
        packageConfig.setEntity("dao.entity");
        packageConfig.setMapper("dao.mapper");
        packageConfig.setService("service");
        packageConfig.setServiceImpl("service.impl");
        packageConfig.setController("api");

        // 替换文件生成位置
        List<FileOutConfig> fileOutConfigList = new ArrayList();
        fileOutConfigList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String file = System.getProperty("user.dir") + "/src/main/resources/mapper/"+moduleName+"/" + tableInfo.getEntityName () + "Mapper.xml";
                if(new File(file).exists() && !fileOverride){
                    System.out.println("请注意配置fileOverride属性! 小心代码被覆盖.");
                    return null;
                }
                return file;
            }
        });
        injectionConfig.setFileOutConfigList(fileOutConfigList);

        autoGenerator.setPackageInfo(packageConfig);
        autoGenerator.setCfg(injectionConfig);
        // 执行生成
        autoGenerator.execute();
        // 打印注入设置
        System.err.println(autoGenerator.getCfg().getMap().get("abc"));
    }

}
